<?php

class RatingManager
{
	private static function GetAvgSql($field)
	{
		return 'ROUND( AVG(' . $field . ')) AS ' . $field;
	}
	
	public static function GetAverages($user)
	{
		$bean = R::GetRow( 'select ' .
			self::GetAvgSql('accurate') . ',' .
			self::GetAvgSql('friendly') . ',' .
			self::GetAvgSql('helpful') . ',' .
			self::GetAvgSql('creative') . ',' .
			self::GetAvgSql('critical') . ',' .
			self::GetAvgSql('friendly') . ',' .
			self::GetAvgSql('gooder') . ',' .
			self::GetAvgSql('helpful') . ',' .
			self::GetAvgSql('trustworthy') .
			' from rating where to_user=\'' . $user . '\'');
		return (object)$bean;
	}
	
	public static function UpdateRating($by_user, $to_user, $accurate, $creative, $critical, $friendly, $gooder, $helpful, $trustworthy, $comment)
	{
		if(!$bean = R::findOne('rating', 'by_user=\'' .$by_user . '\' and to_user=\'' . $to_user . '\''))
		{
			$bean = R::dispense('rating');
			$bean->by_user = $by_user;
			$bean->to_user = $to_user;
		}		
		$bean->when_datetime = date('y.m.d H:i:s');
		$bean->accurate = $accurate;
		$bean->creative = $creative;
		$bean->critical = $critical;
		$bean->friendly = $friendly;
		$bean->gooder = $gooder;
		$bean->helpful = $helpful;
		$bean->trustworthy = $trustworthy;
		$bean->comment = $comment;
		R::store($bean);
		RatingUpdateManager::AddRatingUpdate($by_user, $to_user, $accurate, $creative, $critical, $friendly, $gooder, $helpful, $trustworthy, $comment);
		return true;
	}
	
	public static function GetRating($by_user, $to_user)
	{
		return R::findOne('rating', 'by_user=\'' .$by_user . '\' and to_user=\'' . $to_user . '\'');
	}
	
	public static function GetRatingsToUser($to_user, $page = 0)
	{
		return aa2oa(R::getAll('SELECT * FROM rating WHERE to_user=\'' . $to_user . '\' ORDER BY when_datetime DESC LIMIT ' . ($page * 20) . ', 20'));
	}
	
	public static function CountRatingsToUser($to_user)
	{
		return R::getCell('SELECT COUNT(to_user) FROM rating WHERE to_user=\'' . $to_user . '\'');
	}
	
	public static function GetRatingsByUser($by_user)
	{
		return aa2oa(R::getAll('SELECT * FROM rating WHERE by_user=\'' . $by_user . '\' ORDER BY when_datetime DESC'));
	}
	
	public static function CountRatingsByUser($user)
	{
		return R::getCell('SELECT COUNT(by_user) FROM rating WHERE by_user=\'' . $user . '\'');
	}
}